using System;
using Csla;
using ENT.GP.Datos.MysqlHelper;
using System.Data;

namespace ENT.GP.Core.Autenticacion
{
    [Serializable]
    public class Usuario : BusinessBase<Usuario>
    {
        #region Business Methods

        private static PropertyInfo<int> IdUsuarioProperty = RegisterProperty<int>(o => o.IdUsuario, "Name");
        public int IdUsuario
        {
            get { return GetProperty(IdUsuarioProperty); }
            set { SetProperty(IdUsuarioProperty, value); }
        }

        private static PropertyInfo<int> IdRolProperty = RegisterProperty<int>(o => o.IdRol, "Name");
        public int IdRol
        {
            get { return GetProperty(IdRolProperty); }
            set { SetProperty(IdRolProperty, value); }
        }

        private static PropertyInfo<string> NombreProperty = RegisterProperty<string>(o => o.Nombre, "Name");
        public string Nombre
        {
            get { return GetProperty(NombreProperty); }
            set { SetProperty(NombreProperty, value); }
        }

        private static PropertyInfo<string> ApellidoProperty = RegisterProperty<string>(o => o.Apellido, "Name");
        public string Apellido
        {
            get { return GetProperty(ApellidoProperty); }
            set { SetProperty(ApellidoProperty, value); }
        }

        private static PropertyInfo<string> LoginProperty = RegisterProperty<string>(o => o.Login, "Name");
        public string Login
        {
            get { return GetProperty(LoginProperty); }
            set { SetProperty(LoginProperty, value); }
        }

        private static PropertyInfo<string> ClaveProperty = RegisterProperty<string>(o => o.Clave, "Name");
        public string Clave
        {
            get { return GetProperty(ClaveProperty); }
            set { SetProperty(ClaveProperty, value); }
        }

        private static PropertyInfo<string> MailProperty = RegisterProperty<string>(o => o.Mail, "Name");
        public string Mail
        {
            get { return GetProperty(MailProperty); }
            set { SetProperty(MailProperty, value); }
        }

        private static PropertyInfo<string> TelefonoProperty = RegisterProperty<string>(o => o.Telefono, "Name");
        public string Telefono
        {
            get { return GetProperty(TelefonoProperty); }
            set { SetProperty(TelefonoProperty, value); }
        }

        //Nuevo Id Empresa
        private static PropertyInfo<int> IDEmpresaProperty = RegisterProperty<int>(o => o.IDEmpresa, "Name");
        public int IDEmpresa
        {
            get { return GetProperty(IDEmpresaProperty); }
            set { SetProperty(IDEmpresaProperty, value); }
        }





        public static bool VerificarLogin(string Usuario, int IDEmpresa)
        {
            return ExisteUsuarioCommand.Execute(Usuario, IDEmpresa);
        }

        public static bool ActualizarEstado(int Id,string Estado)
        {
            return ActualizarEstadoCommand.Execute(Id, Estado);
        }
        #endregion

        #region Validation Rules

        protected override void AddBusinessRules()
        {
            // TODO: add validation rules
            //ValidationRules.AddRule(RuleMethod, "");
        }

        #endregion

        #region Authorization Rules

        protected override void AddAuthorizationRules()
        {
            // TODO: add authorization rules
            //AuthorizationRules.AllowWrite("Name", "Role");
        }

        private static void AddObjectAuthorizationRules()
        {
            // TODO: add authorization rules
            //AuthorizationRules.AllowEdit(typeof(Usuario), "Role");
        }

        #endregion

        #region Factory Methods

        public static Usuario NewUsuario()
        {
            return DataPortal.Create<Usuario>();
        }

        public static Usuario GetUsuario(int id)
        {
            return DataPortal.Fetch<Usuario>(
              new SingleCriteria<Usuario, int>(id));
        }

        public static void DeleteUsuario(int id)
        {
            DataPortal.Delete(new SingleCriteria<Usuario, int>(id));
        }

        private Usuario()
        { /* Require use of factory methods */ }

        #endregion

        #region Data Access

        [RunLocal]
        protected override void DataPortal_Create()
        {
            // TODO: load default values
            // omit this override if you have no defaults to set
            base.DataPortal_Create();
        }

        private void DataPortal_Fetch(SingleCriteria<Usuario, int> criteria)
        {
            DataSet dsDatos = new DataSet();
            HelperMySql objhm = HelperMySql.ObtenerConexion("");
            MySql.Data.MySqlClient.MySqlParameter[] parametros = new MySql.Data.MySqlClient.MySqlParameter[2];
            parametros[0] = new MySql.Data.MySqlClient.MySqlParameter("IDU", criteria.Value);
            parametros[1] = new MySql.Data.MySqlClient.MySqlParameter("OPC", 1);
            dsDatos = objhm.EjecutarStoreProcedure(parametros, "Obtener_Usuario");
            if (dsDatos.Tables[0].Rows.Count > 0)
            {
                LoadProperty(IdUsuarioProperty , Convert.ToInt32(dsDatos.Tables[0].Rows[0][0].ToString()));
                LoadProperty(IdRolProperty, Convert.ToInt32(dsDatos.Tables[0].Rows[0][1].ToString()));
                LoadProperty(NombreProperty, dsDatos.Tables[0].Rows[0][2].ToString());
                LoadProperty(ApellidoProperty, dsDatos.Tables[0].Rows[0][3].ToString());
                LoadProperty(LoginProperty, dsDatos.Tables[0].Rows[0][4].ToString());
                LoadProperty(ClaveProperty, dsDatos.Tables[0].Rows[0][5].ToString());
                LoadProperty(TelefonoProperty, dsDatos.Tables[0].Rows[0][8].ToString());
                LoadProperty(MailProperty, dsDatos.Tables[0].Rows[0][9].ToString());
            }
        }

        [Transactional(TransactionalTypes.TransactionScope)]
        protected override void DataPortal_Insert()
        {
            HelperMySql objhm = HelperMySql.ObtenerConexion("");
            MySql.Data.MySqlClient.MySqlParameter[] parametros = new MySql.Data.MySqlClient.MySqlParameter[8];
            try
            {
                parametros[0] = new MySql.Data.MySqlClient.MySqlParameter("ROL_ID", IdRol );
                parametros[1] = new MySql.Data.MySqlClient.MySqlParameter("USER_NOMBRE", Nombre);
                parametros[2] = new MySql.Data.MySqlClient.MySqlParameter("USER_APELLIDO", Apellido);
                parametros[3] = new MySql.Data.MySqlClient.MySqlParameter("USER_USUARIO", Login);
		        parametros[4] = new MySql.Data.MySqlClient.MySqlParameter("USER_CLAVE", Clave);
                parametros[5] = new MySql.Data.MySqlClient.MySqlParameter("USER_TELF", Telefono);
                parametros[6] = new MySql.Data.MySqlClient.MySqlParameter("USER_MAIL", Mail);
                parametros[7] = new MySql.Data.MySqlClient.MySqlParameter("IDEMPR1", IDEmpresa);
                objhm.EjecutarStoreProcedure("Insertar_Usuario", parametros);
            }
            catch (Exception)
            {

                throw;
            }
        }

        [Transactional(TransactionalTypes.TransactionScope)]
        protected override void DataPortal_Update()
        {
            HelperMySql objhm = HelperMySql.ObtenerConexion("");
            MySql.Data.MySqlClient.MySqlParameter[] parametros = new MySql.Data.MySqlClient.MySqlParameter[9];
            try
            {
                parametros[0] = new MySql.Data.MySqlClient.MySqlParameter("IDR", IdRol);
                parametros[1] = new MySql.Data.MySqlClient.MySqlParameter("NU", Nombre);
                parametros[2] = new MySql.Data.MySqlClient.MySqlParameter("AU", Apellido);
                parametros[3] = new MySql.Data.MySqlClient.MySqlParameter("UN", Login);
                parametros[4] = new MySql.Data.MySqlClient.MySqlParameter("PW", Clave);
                parametros[5] = new MySql.Data.MySqlClient.MySqlParameter("EU", "ACTIVO");
                parametros[6] = new MySql.Data.MySqlClient.MySqlParameter("TEL", Telefono);
                parametros[7] = new MySql.Data.MySqlClient.MySqlParameter("ML", Mail);
                parametros[8] = new MySql.Data.MySqlClient.MySqlParameter("IDU", IdUsuario);

                objhm.EjecutarStoreProcedure("Actualizar_Usuario", parametros);
            }
            catch (Exception)
            {
                throw;
            }
        }

        [Transactional(TransactionalTypes.TransactionScope)]
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new SingleCriteria<Usuario, int>(this.IdUsuario));
        }

        [Transactional(TransactionalTypes.TransactionScope)]
        private void DataPortal_Delete(SingleCriteria<Usuario, int> criteria)
        {
            // TODO: delete values
        }

        #endregion
    }

    [Serializable]
    public class ExisteUsuarioCommand : CommandBase
    {
        private string _usuario;
        private int _IDEmpresa;
        #region Authorization Methods

        public static bool CanExecuteCommand()
        {
            // TODO: customize to check user role
            //return Csla.ApplicationContext.User.IsInRole("Role");
            return true;
        }

        #endregion

        #region Factory Methods

        public static bool Execute(string usuario, int IDEmpresa)
        {
            if (!CanExecuteCommand())
                throw new System.Security.SecurityException("Not authorized to execute command");

            ExisteUsuarioCommand cmd = new ExisteUsuarioCommand(usuario, IDEmpresa);
            cmd.BeforeServer();
            cmd = DataPortal.Execute<ExisteUsuarioCommand>(cmd);
            cmd.AfterServer();
            return cmd.Result;
        }

        private ExisteUsuarioCommand(string usuario, int IDEmpresa)
        { /* require use of factory methods */
            _usuario = usuario;
            _IDEmpresa = IDEmpresa;
            _result = false;
        }

        #endregion

        #region Client-side Code

        // TODO: add your own fields and properties
        bool _result;

        public bool Result
        {
            get { return _result; }
        }

        private void BeforeServer()
        {
            // TODO: implement code to run on client
            // before server is called
        }

        private void AfterServer()
        {
            // TODO: implement code to run on client
            // after server is called
        }

        #endregion

        #region Server-side Code

        protected override void DataPortal_Execute()
        {
            int numeroUsuario = 0;object valret;
            HelperMySql objhm = HelperMySql.ObtenerConexion("");
            MySql.Data.MySqlClient.MySqlParameter[] parametros = new MySql.Data.MySqlClient.MySqlParameter[2];
            try
            {
                parametros[0] = new MySql.Data.MySqlClient.MySqlParameter("Usuario", _usuario);
                parametros[1] = new MySql.Data.MySqlClient.MySqlParameter("IDEmpresa1", _IDEmpresa);

                valret = objhm.EjecutarStoreProcedure("Comprobar_Login", parametros, 1);
                int.TryParse(valret.ToString(),out numeroUsuario);
                if (numeroUsuario == 0)
                    _result = false;
                else
                    _result = true;
            }
            catch (Exception)
            {
                throw;
            }
        }

        #endregion
    }

    [Serializable]
    public class ActualizarEstadoCommand : CommandBase
    {
        private int _id;
        private string _estado;
        #region Authorization Methods

        public static bool CanExecuteCommand()
        {
            // TODO: customize to check user role
            //return Csla.ApplicationContext.User.IsInRole("Role");
            return true;
        }

        #endregion

        #region Factory Methods

        public static bool Execute(int id,string estado)
        {
            if (!CanExecuteCommand())
                throw new System.Security.SecurityException("Not authorized to execute command");

            ActualizarEstadoCommand cmd = new ActualizarEstadoCommand(id, estado);
            cmd.BeforeServer();
            cmd = DataPortal.Execute<ActualizarEstadoCommand>(cmd);
            cmd.AfterServer();
            return cmd.Result;
        }

        private ActualizarEstadoCommand(int id,string estado)
        { /* require use of factory methods */
            _id = id;
            _estado = estado;
            _result = false;
        }

        #endregion

        #region Client-side Code

        // TODO: add your own fields and properties
        bool _result;

        public bool Result
        {
            get { return _result; }
        }

        private void BeforeServer()
        {
            // TODO: implement code to run on client
            // before server is called
        }

        private void AfterServer()
        {
            // TODO: implement code to run on client
            // after server is called
        }

        #endregion

        #region Server-side Code

        protected override void DataPortal_Execute()
        {
          
            HelperMySql objhm = HelperMySql.ObtenerConexion("");
            MySql.Data.MySqlClient.MySqlParameter[] parametros = new MySql.Data.MySqlClient.MySqlParameter[2];
            try
            {
                parametros[0] = new MySql.Data.MySqlClient.MySqlParameter("IDU", _id);
                parametros[1] = new MySql.Data.MySqlClient.MySqlParameter("ML", _estado);
                objhm.EjecutarStoreProcedure("Actualizar_Usuario_Estado", parametros,2);
              
            }
            catch (Exception)
            {
                throw;
            }
        }

        #endregion
    }




}
